"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/components/ui/use-toast"
import { fetchUsers, updateUserRole, freezeUser, unfreezeUser, fetchAuditLogs } from "@/lib/api"

interface User {
  id: string
  username: string
  email: string
  role: "admin" | "user"
  status: "active" | "frozen"
}

interface AuditLog {
  timestamp: string
  adminId: string
  actionType: string
  targetUser: string
  details: string
}

export default function AdminPage() {
  const [users, setUsers] = useState<User[]>([])
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [loading, setLoading] = useState(true)
  const [confirmAction, setConfirmAction] = useState<{
    userId: string
    action: "freeze" | "unfreeze"
  } | null>(null)

  const { toast } = useToast()

  useEffect(() => {
    const loadData = async () => {
      try {
        const userData = await fetchUsers()
        const logsData = await fetchAuditLogs()
        setUsers(userData)
        setLogs(logsData)
      } catch (error) {
        console.error("Failed to load admin data:", error)
        toast({
          title: "加载失败",
          description: "无法加载用户数据，请稍后再试",
          variant: "destructive",
        })
      } finally {
        setLoading(false)
      }
    }

    loadData()
  }, [toast])

  const handleRoleChange = async (userId: string, newRole: "admin" | "user") => {
    try {
      await updateUserRole(userId, newRole)
      setUsers(users.map((user) => (user.id === userId ? { ...user, role: newRole } : user)))
      toast({
        title: "权限更新成功",
        description: `用户权限已更新为${newRole === "admin" ? "管理员" : "普通用户"}`,
      })
    } catch (error) {
      console.error("Failed to update user role:", error)
      toast({
        title: "更新失败",
        description: "无法更新用户权限，请稍后再试",
        variant: "destructive",
      })
    }
  }

  const handleConfirmAction = async () => {
    if (!confirmAction) return

    const { userId, action } = confirmAction

    try {
      if (action === "freeze") {
        await freezeUser(userId)
        setUsers(users.map((user) => (user.id === userId ? { ...user, status: "frozen" } : user)))
        toast({
          title: "账户已冻结",
          description: "用户账户已成功冻结",
        })
      } else {
        await unfreezeUser(userId)
        setUsers(users.map((user) => (user.id === userId ? { ...user, status: "active" } : user)))
        toast({
          title: "账户已解冻",
          description: "用户账户已成功解冻",
        })
      }
    } catch (error) {
      console.error(`Failed to ${action} user:`, error)
      toast({
        title: "操作失败",
        description: `无法${action === "freeze" ? "冻结" : "解冻"}用户账户，请稍后再试`,
        variant: "destructive",
      })
    } finally {
      setConfirmAction(null)
    }
  }

  const handleExportLogs = () => {
    const csv = [
      ["操作时间", "管理员 ID", "操作类型", "目标用户", "操作详情"],
      ...logs.map((log) => [log.timestamp, log.adminId, log.actionType, log.targetUser, log.details]),
    ]
      .map((row) => row.join(","))
      .join("\n")

    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" })
    const url = URL.createObjectURL(blob)
    const link = document.createElement("a")
    link.href = url
    link.setAttribute("download", `audit_logs_${new Date().toISOString().split("T")[0]}.csv`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    )
  }

  return (
    <div className="w-full mx-auto bg-gray-100 min-h-screen">
      {/* 顶部导航 */}
      <div className="flex items-center justify-between px-8 py-4 border-b bg-white">
        <div className="flex items-center space-x-2">
          <Image src="/images/signature.png" alt="签名认证系统" width={40} height={40} />
          <span className="text-xl font-bold">签名认证系统</span>
        </div>
        <div className="flex items-center space-x-4">
          <span className="text-sm text-gray-600">管理员 ID：admin_001</span>
          <Link href="/dashboard">
            <Button variant="outline" size="sm">
              返回系统首页
            </Button>
          </Link>
        </div>
      </div>

      {/* 用户权限管理 */}
      <div className="px-8 py-6">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl font-bold text-gray-900">用户权限管理</h1>
          <Button variant="outline" className="flex items-center">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5 mr-2"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <polyline points="1 4 1 10 7 10"></polyline>
              <polyline points="23 20 23 14 17 14"></polyline>
              <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path>
            </svg>
            刷新列表
          </Button>
        </div>

        <div className="bg-white rounded-lg shadow">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">ID</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">用户名</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">邮箱</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">权限设置</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {users.map((user) => (
                <tr key={user.id}>
                  <td className="px-6 py-4 text-sm text-gray-900">{user.id}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{user.username}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{user.email}</td>
                  <td className="px-6 py-4">
                    <Select
                      value={user.role}
                      onValueChange={(value: string) => handleRoleChange(user.id, value as "admin" | "user")}
                    >
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="选择权限" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="user">普通用户</SelectItem>
                        <SelectItem value="admin">管理员</SelectItem>
                      </SelectContent>
                    </Select>
                  </td>
                  <td className="px-6 py-4">
                    {user.status === "active" ? (
                      <Button
                        variant="destructive"
                        onClick={() => setConfirmAction({ userId: user.id, action: "freeze" })}
                      >
                        冻结账户
                      </Button>
                    ) : (
                      <Button
                        className="bg-green-600 hover:bg-green-700"
                        onClick={() => setConfirmAction({ userId: user.id, action: "unfreeze" })}
                      >
                        解冻账户
                      </Button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 操作日志 */}
      <div className="px-8 py-6">
        <div className="flex justify-between items-center mb-8">
          <h2 className="text-2xl font-bold text-gray-900">操作日志</h2>
          <Button variant="outline" className="flex items-center" onClick={handleExportLogs}>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5 mr-2"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
              <polyline points="7 10 12 15 17 10"></polyline>
              <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            导出日志
          </Button>
        </div>

        <div className="bg-white rounded-lg shadow">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">操作时间</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">管理员 ID</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">操作类型</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">目标用户</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">操作详情</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {logs.map((log, index) => (
                <tr key={index}>
                  <td className="px-6 py-4 text-sm text-gray-900">{log.timestamp}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{log.adminId}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{log.actionType}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{log.targetUser}</td>
                  <td className="px-6 py-4 text-sm text-gray-900">{log.details}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 确认操作模态框 */}
      <Dialog open={!!confirmAction} onOpenChange={(open) => !open && setConfirmAction(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认操作</DialogTitle>
            <DialogDescription>
              {confirmAction?.action === "freeze"
                ? "确定要冻结该用户账户吗？冻结后用户将无法登录系统。"
                : "确定要解冻该用户账户吗？解冻后用户将可以正常登录系统。"}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmAction(null)}>
              取消
            </Button>
            <Button
              variant={confirmAction?.action === "freeze" ? "destructive" : "default"}
              onClick={handleConfirmAction}
            >
              确认
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
